package com.sdk.pay.transfer;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.sdk.pay.transfer.api.PostQrCodeNumberAPI;
import com.sdk.pay.transfer.api.PostQrCodeRemoteInfoAPI;
import com.sdk.pay.transfer.constant.PayContext;
import com.sdk.pay.transfer.listener.UploadStatusListener;
import com.sdk.pay.transfer.model.RemoteInfoModel;
import com.sdk.pay.transfer.model.WECHATBean;
import com.sdk.pay.transfer.provider.ProviderHelper;
import com.sdk.pay.transfer.services.ProductDataService;
import com.sdk.pay.transfer.utils.ActivityHelper;
import com.sdk.pay.transfer.utils.LogUtil;
import com.sdk.pay.transfer.utils.UploadDataUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import static com.sdk.pay.transfer.constant.PayContext.INPUTFOCUS;
import static com.sdk.pay.transfer.constant.PayContext.LOG_CLEAN_LINE;


public class MainActivity extends Activity implements UploadStatusListener {
    EditText ProductMoney;
    EditText ProductTimes;
    EditText ProductAliNum;
    EditText ProductShopCode;
    private TextView LogContent;
    private ScrollView ScrollView_Log;
    public static MainActivity instance;
    private Intent service = null;
    private int count = 0;
    private RemoteInfoModel mRemoteInfoModel = null;
    private Button startButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        PayContext.VerifyAliResult = false;
        PayContext.INPUTFOCUS = false;
        initView();
        instance = this;
        UploadDataUtil.getInstance().setUploadStatusListener(this);
        onContinue();
    }

    private void initView() {
        ProductMoney = (EditText) findViewById(R.id.ProductMoney);
        ProductTimes = (EditText) findViewById(R.id.ProductTimes);
        ProductAliNum = (EditText) findViewById(R.id.ProductAliNum);
        ProductShopCode = (EditText) findViewById(R.id.ProductShopCode);
        LogContent = (TextView) findViewById(R.id.LogContent);
        ScrollView_Log = (ScrollView) findViewById(R.id.ScrollView_Log);
        startButton = (Button) findViewById(R.id.startBtn);
    }

    @Override
    protected void onDestroy() {
        log("MainActivity onDestroy");
        super.onDestroy();
    }

    @Override
    protected void onStart() {
        super.onStart();
        upLoadData();
    }

    private void upLoadData() {
        LogUtil.log("onstart");
        if (!INPUTFOCUS && !PayContext.VerifyAliResult) {
            return;
        }
        UploadDataUtil.getInstance().uploadDatasInOrder(this);
    }

    public void onContinue() {
        List<WECHATBean> beanList = ProviderHelper.get_ListBean_Without_CodeUrl(this);
        if (beanList == null || beanList.size() < 1) {
            startButton.setText(R.string.start_product);
        } else {
            startButton.setText(R.string.continue_product);
        }
    }

    public void onSubmit(View view) {
        Button button = (Button) view;
        if (button.getText().toString().equals(getString(R.string.continue_product))) {
            view.setVisibility(View.GONE);
            ActivityHelper.startQRActivity();
            return;
        }
        if (!INPUTFOCUS && !PayContext.VerifyAliResult) {
            log("请先完成微信账号验证!");
            return;
        }
        String account = ProductShopCode.getText().toString();
        String number = ProductAliNum.getText().toString();
        String money = ProductMoney.getText().toString();
        String number1 = ProductTimes.getText().toString();
        if (TextUtils.isEmpty(account.trim()) || TextUtils.isEmpty(number.trim()) ||
                TextUtils.isEmpty(money.trim()) || TextUtils.isEmpty(number1.trim())) {
            Toast.makeText(this, "请补全资料", Toast.LENGTH_SHORT).show();
            return;
        }
        if (INPUTFOCUS) {
            mRemoteInfoModel = new RemoteInfoModel();
            mRemoteInfoModel.setSys_Code("JFT");
            mRemoteInfoModel.setPlatform("0");
            mRemoteInfoModel.setReceive_Account(account);
            mRemoteInfoModel.setPlatform_Number(number);
            mRemoteInfoModel.setMoney(money);
            mRemoteInfoModel.setTask_Number(number1);
        }
        if (mRemoteInfoModel == null) {
            Toast.makeText(this, "获取参数数据错误,请重新获取！", Toast.LENGTH_SHORT).show();
            return;
        }
        if (mRemoteInfoModel.getPlatform_Number().length() != 3 || mRemoteInfoModel.getReceive_Account().length() != 8) {
            Toast.makeText(this, "商户信息设置错误！", Toast.LENGTH_SHORT).show();
            return;
        }
        view.setVisibility(View.GONE);
        if (INPUTFOCUS) {
            getCurrentQRCodeNumber(mRemoteInfoModel);
        } else {
            doProductQrCode(mRemoteInfoModel);
        }
    }

    private void getCurrentQRCodeNumber(final RemoteInfoModel model) {
        new PostQrCodeNumberAPI().PostQrCodeNumber(model,
                new PostQrCodeNumberAPI.Listener() {
                    @Override
                    public void onSuccess(String message) {
                        model.setScreenshot_Number(message);
                        doProductQrCode(model);
                    }

                    @Override
                    public void onFailure(int code, String message) {
                        log("getCurrentQRCodeNumber onFailure message : " + message);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                findViewById(R.id.startBtn).setVisibility(View.VISIBLE);
                            }
                        });
                    }
                });
    }

    private void getRemoteMsg() {
        new PostQrCodeRemoteInfoAPI().PostQrCodeRemoteInfo(new PostQrCodeRemoteInfoAPI.Listener() {
            @Override
            public void onSuccess(String message) {
                log("getRemoteMsg : " + message);
                mRemoteInfoModel = new RemoteInfoModel();
                try {
                    JSONObject object = new JSONObject(message);
                    mRemoteInfoModel.setPlatform(object.getString("Platform"));
                    mRemoteInfoModel.setReceive_Account(object.getString("Receive_Account"));
                    mRemoteInfoModel.setPlatform_Number(object.getString("Platform_Number"));
                    mRemoteInfoModel.setMoney(object.getString("Money"));
                    mRemoteInfoModel.setScreenshot_Number(object.getString("Screenshot_Number"));
                    mRemoteInfoModel.setSys_Code(object.getString("Sys_Code"));
                    mRemoteInfoModel.setTask_Number(object.getString("Task_Number"));
                    mRemoteInfoModel.setTask_Account(object.getString("Task_Account"));

                    PayContext.SYSTEM = mRemoteInfoModel.getSys_Code();
                    PayContext.VerifyAliAccout = mRemoteInfoModel.getTask_Account();

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ProductMoney.setText(mRemoteInfoModel.getMoney());
                            ProductTimes.setText(mRemoteInfoModel.getTask_Number());
                            ProductAliNum.setText(mRemoteInfoModel.getPlatform_Number());
                            ProductShopCode.setText(mRemoteInfoModel.getReceive_Account());
                        }
                    });

                } catch (JSONException e) {
                    e.printStackTrace();
                    log("getRemoteMsg JSONObject error : " + e.getMessage());
                }
            }

            @Override
            public void onFailure(int code, String message) {
                log("getRemoteMsg onFailure message : " + message);
            }
        });
    }

    private void doProductQrCode(RemoteInfoModel model) {
        try {
            log("MainActivity startService");
            int count = Integer.parseInt(model.getTask_Number());
            if (count < 1) {
                log("count values must be greater than 0 ");
                return;
            }
            service = new Intent(MainActivity.this, ProductDataService.class);
            service.putExtra("platform", model.getPlatform());
            service.putExtra("money", model.getMoney());
            service.putExtra("count", count);
            service.putExtra("platNum", model.getPlatform_Number());
            service.putExtra("shopCode", model.getReceive_Account());
            service.putExtra("currentIndex", model.getScreenshot_Number());
            startService(service);
        } catch (Exception e) {
            e.printStackTrace();
            log("MainActivity exception" + e.getMessage());
        }
    }

    public void verifyWechat(View view) {
        PayContext.VerifyWechat = 1;
        ActivityHelper.startPersonCenterActivity();
    }

    public void getRemoteInfo(View view) {
        log("正在获取服务器信息..");
        getRemoteMsg();
    }

    public void log(final String content) {
        try {
            LogUtil.log(content);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    count++;
                    if (count == LOG_CLEAN_LINE) {
                        LogContent.setText("日志输出：\n");
                        count = 0;
                    }
                    LogContent.append(content + "\n");
                    ScrollView_Log.fullScroll(ScrollView.FOCUS_DOWN);//滚动到底部
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void finish() {
        /*
         * 记住不要执行此句 super.finish(); 因为这是父类已经实现了改方法
         * 设置该activity永不过期，即不执行onDestroy()
         */
        moveTaskToBack(true);
    }

    @Override
    public void uploadStatus(final boolean status) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (status) {
                    findViewById(R.id.startBtn).setVisibility(View.VISIBLE);
                } else {
                    log("上传中请稍后！");
                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.cleanLog:
                LogContent.setText("日志输出：\n");
                break;
            case R.id.cleanDb:
                ProviderHelper.deleteWechat(this);
                break;
            case R.id.switchInputType:
                INPUTFOCUS = !INPUTFOCUS;
                switchInputStatus();
                break;
            case R.id.exit:
                android.os.Process.killProcess(android.os.Process.myPid());
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void switchInputStatus() {
        mRemoteInfoModel = null;
        ProductMoney.setFocusable(INPUTFOCUS);
        ProductMoney.setFocusableInTouchMode(INPUTFOCUS);
        ProductTimes.setFocusable(INPUTFOCUS);
        ProductTimes.setFocusableInTouchMode(INPUTFOCUS);
        ProductAliNum.setFocusable(INPUTFOCUS);
        ProductAliNum.setFocusableInTouchMode(INPUTFOCUS);
        ProductShopCode.setFocusable(INPUTFOCUS);
        ProductShopCode.setFocusableInTouchMode(INPUTFOCUS);
        if (INPUTFOCUS) {
            log("当前模式为手动输入数据模式");
        } else {
            log("当前模式为服务器获取数据模式");
        }
        PayContext.VerifyAliResult = INPUTFOCUS;
    }

    public void cleanParam() {
        ProductShopCode.setText("");
        ProductAliNum.setText("");
        ProductMoney.setText("");
        ProductTimes.setText("");
        if (INPUTFOCUS) {
            return;
        }
        PayContext.VerifyAliResult = false;
        startButton.setText(R.string.start_product);
    }
}